package com.example.coreshopapp.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.example.coreshopapp.R;
import com.example.coreshopapp.app.AppConfig;
import com.example.coreshopapp.app.AppManager;
import com.example.coreshopapp.app.Constants;
import com.example.coreshopapp.app.lifecycle.IComponentContainer;
import com.example.coreshopapp.app.lifecycle.LifeCycleComponent;
import com.example.coreshopapp.app.lifecycle.LifeCycleComponentManager;
import com.example.coreshopapp.net.BaseApplication;
import com.example.coreshopapp.ui.LoginActivity;
import com.example.coreshopapp.weight.CustomProgressDialog;

import java.util.Locale;

public class BaseActivity extends AppCompatActivity implements IComponentContainer {
    private LifeCycleComponentManager mComponentContainer = new LifeCycleComponentManager();
    protected CustomProgressDialog dialog;
    protected boolean isLimitApp = false;//是否限制不可退出APP
    public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000; //定义屏蔽HOME键标志

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //先关闭，发布时打开
//        Window window = getWindow();//隐藏最下面的NAVIGATION状态栏,导航栏.点击屏幕也不弹出
//        WindowManager.LayoutParams params = window.getAttributes();
//        params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE;
//        window.setAttributes(params);

//        setActionBar();

        // loading
        dialog = new CustomProgressDialog(this, R.style.CustomProgressDialog).setMessage("加载中...");
        AppManager.getAppManager().addActivity(this);
        AppConfig.init(this);
        BaseApplication baseApplication = BaseApplication.getInstance();

//        isLimitApp =  BaseApplication.getInstance().getSpUtil().getBoolean(Constants.spClass.SP_LIMIT_APP, false);
//        if (isLimitApp){
//            this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);//屏蔽Home键
//        }

        //去掉输入法,手机的，不要显示启用以下代码  软键盘
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

    }

    public static void hideAllInputMethod(Activity act) {
        InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
        //软键盘如果已经打开就要关闭
        if (imm.isActive() == true) {
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    public static void showAllInputMethod(Activity act) {
        InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
        //软键盘如果已经打开就要关闭
        if (imm.isActive() == false) {
            imm.toggleSoftInput(0, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    public void setActionBar() {
        ActionBar actionBar = getSupportActionBar();
        // 设置ActionBar的内边距为0
//        actionBar.setCustomView(isSolidAction ? R.layout.layout_top_solid_bar : R.layout.layout_top_bar);
        actionBar.setCustomView(R.layout.layout_top_bar);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.getCustomView().setPadding(0, 0, 0, 0);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    // 打开提示框
    protected void showLoadingDialog(int res_id) {
        dialog.setMessage(getString(res_id));
        dialog.show();
    }

    // 打开提示框
    protected void showLoadingDialog(String str) {
        dialog.setMessage(str);
        dialog.show();
    }

    // 关闭提示框
    protected void hideLoadingDialog() {
        dialog.dismiss();
    }

    // 隐藏顶部导航
    protected void hideTopBar() {
        getSupportActionBar().hide();
    }

    // 自定义顶部导航文字
    public void setSubmit(String text) {
        Button btn = (Button) (getSupportActionBar().getCustomView().findViewById(R.id.btn_submit));
        if (TextUtils.isEmpty(text)) {
            btn.setVisibility(View.GONE);
        } else {
            btn.setVisibility(View.VISIBLE);
            btn.setText(text);
        }
    }

    public void setBack(String text) {
        Button btn = (Button) (getSupportActionBar().getCustomView().findViewById(R.id.btn_back));
        if (TextUtils.isEmpty(text)) {
            btn.setVisibility(View.GONE);
        } else {
            btn.setVisibility(View.VISIBLE);
            btn.setText(text);
        }
    }

    /**
     * 改变背景颜色
     */
    public void darkenBackground(Float bgcolor) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgcolor;

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }

    protected void onStart() {
        super.onStart();
        mComponentContainer.onBecomesVisibleFromTotallyInvisible();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mComponentContainer.onBecomesPartiallyInvisible();
        if (isLimitApp) {
            //屏蔽菜单键
            ActivityManager activityManager = (ActivityManager) getApplicationContext()
                    .getSystemService(Context.ACTIVITY_SERVICE);
//            activityManager.moveTaskToFront(getTaskId(), 0);
        }
    }

    /**
     * 跳转Activity
     */
    protected void gotoActivity(Class<? extends Activity> activity, Bundle bundle) {
        Intent intent = new Intent(this, activity);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 跳转Activity
     */
    protected void gotoActivity(Class<? extends Activity> activity) {
        Intent intent = new Intent(this, activity);
        startActivity(intent);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    // 跳转时忘记上一页
    protected void gotoActivityFinish(Class<? extends Activity> activity) {
        Intent intent = new Intent(this, activity);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);//创建新任务栈并清空旧栈，跳转后原 Activity 被彻底移除，返回时无法回溯。
        startActivity(intent);
        finish(); // 可选：主动销毁当前Activity，确保无法返回
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    // 返回登录页面
    protected void goLogin(Class<? extends  Activity> activity) {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
        Constants.AppConstVars.sysUser = null;
        Constants.AppConstVars.token = "";
        Constants.AppConstVars.SnInfo = null;
        Constants.AppConstVars.classBillNo = "";
        Constants.AppConstVars.Sn = "";
        Constants.AppConstVars.MemberInfo = null;
    }

    /**
     * 跳转activity for result
     */
    protected void gotoActivityForResult(Class<? extends Activity> activity, Bundle bundle, int requestCode) {
        Intent intent = new Intent(this, activity);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * 获取当前activity实例
     */
    protected Activity getActivity() {
        return this;
    }

    public void defaultFinish() {
        finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    /**
     * 返回
     */
    public void goBack(View view) {
        back();
    }

    public void back() {
        defaultFinish();
    }

    public void showShortToast(int id) {
        Toast.makeText(this, getString(id), Toast.LENGTH_SHORT).show();
    }

    public void showShortToast(String content) {
        Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
    }

    public void showShortToast(String content, int i) {
        Toast toast = Toast.makeText(this, content, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
            back();
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void addComponent(LifeCycleComponent component) {
        mComponentContainer.addComponent(component);
    }

    // 切换语言
    public void setLocale(String lang) {
        Locale locale = new Locale(lang);
        Locale.setDefault(locale);

        Configuration config = getResources().getConfiguration();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            config.setLocale(locale);
        } else {
            config.locale = locale;
        }
        getBaseContext().getResources().updateConfiguration(config,
                getBaseContext().getResources().getDisplayMetrics());
    }

    // 全屏模式
    public  void fullScreenMode() {
        // 在Activity的onCreate()中添加以下代码
        View decorView = getWindow().getDecorView();
        int uiOptions = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        decorView.setSystemUiVisibility(uiOptions);
    }

    /**
     * Toast
     * @param context
     * @param text
     */
    public void showtoast(Context context, String text){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.my_toast,
                (ViewGroup) ((Activity) context).findViewById(R.id.custom_toast_container));

        TextView textview = layout.findViewById(R.id.toasttext);
        textview.setText(text);

        Toast toast = new Toast(context);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setView(layout);
        toast.show();
    }

//    public void loadNumber(String type,int numberName) {
//        corecmsnumberdetail load = numberDetailDao.load(Long.parseLong(type));
//        load.setLastNumber(numberName); // 增加number
//        numberDetailDao.insert(load);
//    }


    public AlertDialog createAlertBuilder (Context context, int layout){
      return  AlertDialogSingleton.getInstance().createAlertBuilder(context,layout);
    }

    public void restart() {
        Intent intent = getIntent();
        finish();
        overridePendingTransition(0, 0);
        startActivity(intent);
        overridePendingTransition(0, 0);
    }
}
